<?php

namespace addons\fzdc\controller;

use addons\epay\library\Service;
use addons\fzdc\library\printer;
use addons\fzdc\library\WxWithdrawal;
use app\admin\model\fzdc\goods\Goods;
use app\admin\model\fzdc\goods\SkuProduct;
use app\admin\model\fzdc\message\Push;
use app\admin\model\fzdc\order\Detail;
use app\admin\model\fzdc\prin\Prin;
use app\admin\model\fzdc\store\Auther;
use app\admin\model\fzdc\store\Bank;
use app\admin\model\fzdc\store\Refund;
use app\admin\model\fzdc\store\Revenue;
use app\admin\model\fzdc\store\Sear;
use app\admin\model\fzdc\store\Store;
use app\admin\model\fzdc\store\StoreCollect;
use app\admin\model\fzdc\store\View;
use app\admin\model\fzdc\store\Withdrawal;
use app\admin\model\fzdc\Userdetail;       
use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use fast\Http;
use think\Db;
use think\Log;
use think\Model;
use think\Queue;
use think\Request;
use think\Validate;
use Yansongda\Pay\Pay;
use app\admin\model\fzdc\coupon\Coupon;
use app\admin\model\fzdc\coupon\Receive;
use app\admin\model\fzdc\goods\Type as GoodsType;
use app\admin\model\fzdc\Store as FzdcStore;


class Business extends Api
{
    protected $noNeedLogin = ['print', 'refund'];
    protected $noNeedRight = ['*'];
    protected $config = [];

    public function __construct(Request $request = null)
    {
        $this->config = get_addon_config("fzdc");
        $this->model = new \app\admin\model\fzdc\order\Order;
        $this->modelstore = new Store;
        $this->modelcoupon = new Coupon;
        $this->modeladdress = new \app\admin\model\fzdc\user\Address;
        parent::__construct($request);
    }

    private static $card_type = array(
        'CC' => '信用卡',
        'DC' => '储蓄卡',
    );

    private static $card_icon = array(
        "ICBC" => "/assets/addons/fzdc/img/10cc05c9b2e40d59e47d59ace574542a.png",
        "ABC" => "/assets/addons/fzdc/img/ff19e9593851e57b2cc2e05457e0d193.png",
        "CCB" => "/assets/addons/fzdc/img/4a1bb5a9c1e14927f2a06385c06dfaf2.png",
        "PSBC" => "/assets/addons/fzdc/img/39a77a0d47a3ffb08c9f6a6e7c48adf0.png",
        "CMB" => "/assets/addons/fzdc/img/f1933e6ff6db57fffa7ce68f3d9bb3b9.png",
        "BOC" => "/assets/addons/fzdc/img/d4caac8de977da77e800064d9ffe7974.png",
        "COMM" => "/assets/addons/fzdc/img/9758699b2d53a3b5587ef8b78854b164.png",
        "SPDB" => "/assets/addons/fzdc/img/ac896ae8561c6b28149d78b6be79aeae.png",
        "GDB" => "/assets/addons/fzdc/img/1676e935970ce51d938fdb1b57a8f723.png",
        "CMBC" => "/assets/addons/fzdc/img/1b1c4db302c8ec77558e1a7bf9d2e71b.png",
        "SPABANK" => "/assets/addons/fzdc/img/0fde08030db8707673813e4755d6c7a3.png",
        "CEB" => "/assets/addons/fzdc/img/71880e2c88e9ce7e4999cd7dd482329f.png",
        "CIB" => "/assets/addons/fzdc/img/0af9a08a9d069d4ab083f4ab700bc6db.png",
        "CITIC" => "/assets/addons/fzdc/img/20f4aab9a679762c78fdbe9ec53034e5.png",
    );

    private static $bank_info = array(
        // 热门银行
        "ICBC" => "中国工商银行",
        "ABC" => "中国农业银行",
        "CCB" => "中国建设银行",
        "PSBC" => "中国邮政储蓄银行",
        "CMB" => "招商银行",
        "BOC" => "中国银行",
        "COMM" => "交通银行",
        "SPDB" => "上海浦东发展银行",
        "GDB" => "广东发展银行",
        "CMBC" => "中国民生银行",
        "SPABANK" => "平安银行",
        "CEB" => "中国光大银行",
        "CIB" => "兴业银行",
        "CITIC" => "中信银行",
        // 其他
        "SRCB" => "深圳农村商业银行",
        "BGB" => "广西北部湾银行",
        "SHRCB" => "上海农村商业银行",
        "BJBANK" => "北京银行",
        "WHCCB" => "威海市商业银行",
        "BOZK" => "周口银行",
        "KORLABANK" => "库尔勒市商业银行",
        "SDEB" => "顺德农商银行",
        "HURCB" => "湖北省农村信用社",
        "WRCB" => "无锡农村商业银行",
        "BOCY" => "朝阳银行",
        "CZBANK" => "浙商银行",
        "HDBANK" => "邯郸银行",
        "BOD" => "东莞银行",
        "ZYCBANK" => "遵义市商业银行",
        "SXCB" => "绍兴银行",
        "GZRCU" => "贵州省农村信用社",
        "ZJKCCB" => "张家口市商业银行",
        "BOJZ" => "锦州银行",
        "BOP" => "平顶山银行",
        "HKB" => "汉口银行",
        "NXRCU" => "宁夏黄河农村商业银行",
        "NYBANK" => "广东南粤银行",
        "GRCB" => "广州农商银行",
        "BOSZ" => "苏州银行",
        "HZCB" => "杭州银行",
        "HSBK" => "衡水银行",
        "HBC" => "湖北银行",
        "JXBANK" => "嘉兴银行",
        "HRXJB" => "华融湘江银行",
        "BODD" => "丹东银行",
        "AYCB" => "安阳银行",
        "EGBANK" => "恒丰银行",
        "CDB" => "国家开发银行",
        "TCRCB" => "江苏太仓农村商业银行",
        "NJCB" => "南京银行",
        "ZZBANK" => "郑州银行",
        "DYCB" => "德阳商业银行",
        "YBCCB" => "宜宾市商业银行",
        "SCRCU" => "四川省农村信用",
        "KLB" => "昆仑银行",
        "LSBANK" => "莱商银行",
        "YDRCB" => "尧都农商行",
        "CCQTGB" => "重庆三峡银行",
        "FDB" => "富滇银行",
        "JSRCU" => "江苏省农村信用联合社",
        "JNBANK" => "济宁银行",
        "JINCHB" => "晋城银行JCBANK",
        "FXCB" => "阜新银行",
        "WHRCB" => "武汉农村商业银行",
        "HBYCBANK" => "湖北银行宜昌分行",
        "TZCB" => "台州银行",
        "TACCB" => "泰安市商业银行",
        "XCYH" => "许昌银行",
        "NXBANK" => "宁夏银行",
        "HSBANK" => "徽商银行",
        "JJBANK" => "九江银行",
        "NHQS" => "农信银清算中心",
        "MTBANK" => "浙江民泰商业银行",
        "LANGFB" => "廊坊银行",
        "ASCB" => "鞍山银行",
        "KSRB" => "昆山农村商业银行",
        "YXCCB" => "玉溪市商业银行",
        "DLB" => "大连银行",
        "DRCBCL" => "东莞农村商业银行",
        "GCB" => "广州银行",
        "NBBANK" => "宁波银行",
        "BOYK" => "营口银行",
        "SXRCCU" => "陕西信合",
        "GLBANK" => "桂林银行",
        "BOQH" => "青海银行",
        "CDRCB" => "成都农商银行",
        "QDCCB" => "青岛银行",
        "HKBEA" => "东亚银行",
        "HBHSBANK" => "湖北银行黄石分行",
        "WZCB" => "温州银行",
        "TRCB" => "天津农商银行",
        "QLBANK" => "齐鲁银行",
        "GDRCC" => "广东省农村信用社联合社",
        "ZJTLCB" => "浙江泰隆商业银行",
        "GZB" => "赣州银行",
        "GYCB" => "贵阳市商业银行",
        "CQBANK" => "重庆银行",
        "DAQINGB" => "龙江银行",
        "CGNB" => "南充市商业银行",
        "SCCB" => "三门峡银行",
        "CSRCB" => "常熟农村商业银行",
        "SHBANK" => "上海银行",
        "JLBANK" => "吉林银行",
        "CZRCB" => "常州农村信用联社",
        "BANKWF" => "潍坊银行",
        "ZRCBANK" => "张家港农村商业银行",
        "FJHXBC" => "福建海峡银行",
        "FJNX" => "福建省农村信用社联合社",
        "ZJNX" => "浙江省农村信用社联合社",
        "LZYH" => "兰州银行",
        "JSB" => "晋商银行",
        "BOHAIB" => "渤海银行",
        "CZCB" => "浙江稠州商业银行",
        "YQCCB" => "阳泉银行",
        "SJBANK" => "盛京银行",
        "XABANK" => "西安银行",
        "BSB" => "包商银行",
        "JSBANK" => "江苏银行",
        "FSCB" => "抚顺银行",
        "HNRCU" => "河南省农村信用",
        "XTB" => "邢台银行",
        "HXBANK" => "华夏银行",
        "HNRCC" => "湖南省农村信用社",
        "DYCCB" => "东营市商业银行",
        "ORBANK" => "鄂尔多斯银行",
        "BJRCB" => "北京农村商业银行",
        "XYBANK" => "信阳银行",
        "ZGCCB" => "自贡市商业银行",
        "CDCB" => "成都银行",
        "HANABANK" => "韩亚银行",
        "LYBANK" => "洛阳银行",
        "ZBCB" => "齐商银行",
        "CBKF" => "开封市商业银行",
        "H3CB" => "内蒙古银行",
        "CRCBANK" => "重庆农村商业银行",
        "SZSBK" => "石嘴山银行",
        "DZBANK" => "德州银行",
        "SRBANK" => "上饶银行",
        "LSCCB" => "乐山市商业银行",
        "JXRCU" => "江西省农村信用",
        "JZBANK" => "晋中市商业银行",
        "HZCCB" => "湖州市商业银行",
        "NHB" => "南海农村信用联社",
        "XXBANK" => "新乡银行",
        "JRCB" => "江苏江阴农村商业银行",
        "YNRCC" => "云南省农村信用社",
        "GXRCU" => "广西省农村信用",
        "BZMD" => "驻马店银行",
        "ARCU" => "安徽省农村信用社",
        "GSRCU" => "甘肃省农村信用",
        "LYCB" => "辽阳市商业银行",
        "JLRCU" => "吉林农信",
        "URMQCCB" => "乌鲁木齐市商业银行",
        "XLBANK" => "中山小榄村镇银行",
        "CSCB" => "长沙银行",
        "JHBANK" => "金华银行",
        "BHB" => "河北银行",
        "NBYZ" => "鄞州银行",
        "LSBC" => "临商银行",
        "BOCD" => "承德银行",
        "SDRCU" => "山东农信",
        "NCB" => "南昌银行",
        "TCCB" => "天津银行",
        "WJRCB" => "吴江农商银行",
        "CBBQS" => "城市商业银行资金清算中心",
        "HBRCU" => "河北省农村信用社",
        // 特写, 有个官方公会签约主播留的是『上虞农商银行』,支付宝接口返回的是 ZJNX
        "ZJNX_SY" => "上虞农商银行",
    );
    public function merchant_list(){
        //根据后台生成的二维码
        //展示对应的列表门店信息
          $merchant_id = $this->request->post('merchant_id');  //页码
          $arr = collection(\app\admin\model\fzdc\store\Store::where(["merchant_id" => $merchant_id])->select())->toArray(); 
          $this->success("success", $arr);
        
    }
    public function merchant_info(){
        $user_id = $this->auth->id;
        //判断该用户关联的店铺
     
        $res1 = \app\admin\model\Merchant::where(["user_id" => $user_id])->find();
        $arr=[];
        if(empty($res1)){
                //证明不是商户管理员
                //再查下一下是不是门店管理员
                $res = collection(\app\admin\model\fzdc\store\User::where(["user_id" => $user_id])->select())->toArray();
                if (!$res) {
                    $this->error("该用户尚未关联店铺");
                }
                
                foreach ($res as $key => $value) {
                    # code...
                    $arr[]=Store::get($value['store_id']);
                }
                //有门店
            
        }else{
            $arr = collection(\app\admin\model\fzdc\store\Store::where(["merchant_id" => $res1->id])->select())->toArray(); 
            $res = collection(\app\admin\model\fzdc\store\User::where(["user_id" => $user_id])->select())->toArray();
            foreach ($res as $key => $value) {
                # code...
                $arr[]=Store::get($value['store_id']);
            }
        }
        $this->success("success", $arr);
    }
       //商品列表
    public function shop_goods_list()
    {
        $page = $this->request->post('page') ?? 1;  //页码
        $limit = $this->request->post('limit') ?? 10; //每页显示条数
        $store_id = $this->request->post('store_id');  //门店id
        $res=Goods::where('store_ids',$store_id)->order("id", "desc")->paginate(["page" => $page, "list_rows" => $limit])->each(function ($item) {
                $item->image = cdnurl($item->image, true);
                 $item->goods_type_name = GoodsType::where('id',$item->type_id)->value('name');
        });
        $this->success("success", $res);
    }
    //商品详情
    public function shop_goods_detail(){
            $id = $this->request->post('id');  //分类id
            $res=Goods::where('id',$id)->find();
           $res->image = cdnurl($res->image, true);
            $this->success("success", $res);
    }
    //商品添加
    public function shop_goods_add(){
          $id = $this->request->post('id')??0;  //id
         $type_id = $this->request->post('type_id');  //分类id
        $store_id = $this->request->post('store_id');  //门店id
        $name = $this->request->post('title');  //名称
        $image=$this->request->post('image');  //缩略图
        // $image=$this->request->post('images');  //详情图
        $state=$this->request->post('state');  //状态值
        $shipment=$this->request->post('shipment')??3; //默认是3=均可 1=自取 2=外卖
        $json=$this->request->post('json');
         $weigh=$this->request->post('weigh');//权重
         $type=$this->request->post('type'); //1=单规格 2=多规格
         $price=$this->request->post('price');
         
           $skus=$this->request->post('skus');
       
           $skus=json_decode(htmlspecialchars_decode($skus),true);
          
        //  var_dump($skus);
        //  die;
           
            $merchant_id=FzdcStore::where('id',$store_id)->value('merchant_id')??0;
        //  $merchant_id=
         //数据入库
               Db::startTrans();
               try {
                   
                     if (empty($id)) {
                       $data=[ 
                       'type_id'=>$type_id,
                        'store_ids'=>$store_id,
                        'title'=>$name,
                        'image'=>$image,
                        'images'=>$image,
                        'state'=>$state,
                        'shipment'=>$shipment,
                        'json'=>$json,
                        'weigh'=>$weigh,
                        'type'=>$type,
                        'price'=>$price,
                        'merchant_id'=>$merchant_id
                         ];
                         $goods=Goods::create($data);
                         
                      
                             $this->shop_goods_spec1($goods->id,$skus);
                     
                     }else{
                             $data=[
                             'type_id'=>$type_id,
                              'title'=>$name,
                            'image'=>$image,
                            'images'=>$image,
                            'state'=>$state,
                            'shipment'=>$shipment,
                            'json'=>$json,
                            'weigh'=>$weigh,
                            'type'=>$type,
                            'price'=>$price,
                        ];
                        Goods::update($data,['id'=>$id]);
                            $this->shop_goods_spec1($id,$skus);
                     }
                
                   
                   //
                       Db::commit();
                      
               } catch (\Exception $e) {
                    Log::error("商品创建或修改失败:". $e->getMessage(). " Line:". $e->getLine());
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }
               $this->success("success");
    }
      public  function shop_goods_spec1($id,$row){
        //专门生成多规格的表
        //   $id = $this->request->post('id');  //商品id
        
           $specModel = new \app\admin\model\fzdc\goods\SkuSpec;
            $itemModel = new \app\admin\model\fzdc\goods\SkuItem;
            $productModel = new \app\admin\model\fzdc\goods\SkuProduct;
            
           $specnum=$specModel->where('goods_id', $id)->count();
            if($specnum>0){
                 $specModel->where('goods_id', $id)->delete();
                  $itemModel->where('goods_id', $id)->delete();
                    $productModel->where('goods_id', $id)->delete();
                   
            }
            
           $productSkusStr= $row['productSkusStr'];  //
              $attrGroupsStr = $row['attrGroupsStr'];  //
                 $attrItemsStr =$row['attrItemsStr'];  //
                //  var_dump(json_decode(htmlspecialchars_decode($attrItemsStr),true));
                //  die;
                 $row=[
                     'groups'=>htmlspecialchars_decode($attrGroupsStr),
                        'items'=>htmlspecialchars_decode($attrItemsStr),
                           'skus'=>htmlspecialchars_decode($productSkusStr),
                     ];
                 
        $this->createSpecItem1($id,$row);
    }
     /**
     * 商品规格写入
     *
     * @param [type] $goodsId
     * @param [type] $row
     * @return void
     */
    public function createSpecItem1($goodsId, $row)
    {
        try {
            // $j=json_decode('["规格","温度"]',true);
            // var_dump($j);
            //          die;
            // var_dump($row);
            // die;
            $groups = json_decode($row['groups'], true);
            // var_dump($groups);
            // die;
               
            $skus = json_decode($row['skus'], true);
             
            $items = json_decode($row['items'], true);
            $specModel = new \app\admin\model\fzdc\goods\SkuSpec;
            $itemModel = new \app\admin\model\fzdc\goods\SkuItem;
            $productModel = new \app\admin\model\fzdc\goods\SkuProduct;
            // 写入spec
            $spec = [];
            foreach ($groups as $k => $v) {
                if (!count($items[$k])) {
                    continue;
                }
                $spec[] = ['name' => $v, 'goods_id' => $goodsId];
            }
            $res = $specModel->saveAll($spec);

            // 写入item
            $item = [];
            foreach ($res as $k => $v) {
                foreach ($items[$k] as $kk => $vv) {
                    $item[] = [
                        'name' => $vv,
                        'spec_id' => $v['id'],
                        'goods_id' => $goodsId // 仅为了方便删除
                    ];
                }
            }
            $res = $itemModel->saveAll($item);

            // 写入规格商品
            $product = [];
            foreach ($skus as $k => $v) {
                $v['key'] = $this->getKey($res, $v['attr']);
                $v['goods_id'] = $goodsId;
                unset($v['attr']);
                $product[] = $v;
            }
            $productModel->saveAll($product);
            
            //   $this->success("success");
            return true;
        } catch (Exception $e) {
            throw new Exception('添加出错'); //让外部回滚
        }
    }
    
    public  function shop_goods_spec(){
        //专门生成多规格的表
          $id = $this->request->post('id');  //商品id
        
           $specModel = new \app\admin\model\fzdc\goods\SkuSpec;
            $itemModel = new \app\admin\model\fzdc\goods\SkuItem;
            $productModel = new \app\admin\model\fzdc\goods\SkuProduct;
            
           $specnum=$specModel->where('goods_id', $id)->count();
            if($specnum>0){
                 $specModel->where('goods_id', $id)->delete();
                  $itemModel->where('goods_id', $id)->delete();
                    $productModel->where('goods_id', $id)->delete();
                   
            }
            
              
      
        $store_id = $this->request->post('store_id');  //门店id
           $productSkusStr= $this->request->post('productSkusStr');  //
              $attrGroupsStr = $this->request->post('attrGroupsStr');  //
                 $attrItemsStr = $this->request->post('attrItemsStr');  //
                //  var_dump(json_decode(htmlspecialchars_decode($attrItemsStr),true));
                //  die;
                 $row=[
                     'groups'=>htmlspecialchars_decode($attrGroupsStr),
                        'items'=>htmlspecialchars_decode($attrItemsStr),
                           'skus'=>htmlspecialchars_decode($productSkusStr),
                     ];
                 
        $this->createSpecItem($id,$row);
    }
   /**
     * 商品规格写入
     *
     * @param [type] $goodsId
     * @param [type] $row
     * @return void
     */
    public function createSpecItem($goodsId, $row)
    {
        try {
            // $j=json_decode('["规格","温度"]',true);
            // var_dump($j);
            //          die;
            // var_dump($row);
            // die;
            $groups = json_decode($row['groups'], true);
            // var_dump($groups);
            // die;
               
            $skus = json_decode($row['skus'], true);
             
            $items = json_decode($row['items'], true);
            $specModel = new \app\admin\model\fzdc\goods\SkuSpec;
            $itemModel = new \app\admin\model\fzdc\goods\SkuItem;
            $productModel = new \app\admin\model\fzdc\goods\SkuProduct;
            // 写入spec
            $spec = [];
            foreach ($groups as $k => $v) {
                if (!count($items[$k])) {
                    continue;
                }
                $spec[] = ['name' => $v, 'goods_id' => $goodsId];
            }
            $res = $specModel->saveAll($spec);

            // 写入item
            $item = [];
            foreach ($res as $k => $v) {
                foreach ($items[$k] as $kk => $vv) {
                    $item[] = [
                        'name' => $vv,
                        'spec_id' => $v['id'],
                        'goods_id' => $goodsId // 仅为了方便删除
                    ];
                }
            }
            $res = $itemModel->saveAll($item);

            // 写入规格商品
            $product = [];
            foreach ($skus as $k => $v) {
                $v['key'] = $this->getKey($res, $v['attr']);
                $v['goods_id'] = $goodsId;
                unset($v['attr']);
                $product[] = $v;
            }
            $productModel->saveAll($product);
            
              $this->success("success");
        } catch (Exception $e) {
            throw new Exception('添加出错'); //让外部回滚
        }
    }
    //显示规格
    public function show_skus(){
         // 规格
                $ids = $this->request->post('id');  //商品id
           $specModel = new \app\admin\model\fzdc\goods\SkuSpec;
            // $itemModel = new \app\admin\model\fzdc\goods\SkuItem;
            $productModel = new \app\admin\model\fzdc\goods\SkuProduct;
        $groups = [];
        $items = [];
        $specs = $specModel->with('skuItems')->where('goods_id', $ids)->select();
        $arr = collection($specs)->toArray();
        $itemKey = []; //商品使用
        foreach ($specs as $k => $v) {
            $groups[] = $v['name'];
            $i = [];
            foreach ($v['sku_items'] as $kk => $vv) {
                $i[] = $vv['name'];
                $itemKey[$vv['id']] = $vv['name'];
            }
            $items[] = $i;
        }

        // 商品
        $products = $productModel->where('goods_id', $ids)->select();
        $products = collection($products)->toArray();
        foreach ($products as $k => $v) {
            $keyArr = explode('_', $v['key']);
            $attr = [];
            foreach ($keyArr as $kk => $vv) {
                if (!empty($vv)){
					$attr[] = $itemKey[$vv];
				}
            }
            unset($products[$k]['key'], $products[$k]['id']);
            $products[$k]['attr'] = $attr;
        }
        $this->success("success",['groups' => $groups, 'items' => $items, 'products' => $products]);
        // 渲染到js
      
    }
        /**
     * 为规格商品匹配key值
     *
     * @param [type] $ids
     * @param [type] $attr
     * @return void
     */
    private function getKey($ids, $attr)
    {
        $key = '';
        foreach ($attr as $v) {
            foreach ($ids as $k => $vv) {
                if ($vv->name === $v) {
                    $key .= '_' . $vv->id;
                }
            }
        }
        return ltrim($key, '_');
    }
  //商品分类
    public function shop_cate()
    { 
            $page = $this->request->post('page') ?? 1;  //页码
            $limit = $this->request->post('limit') ?? 100; //每页显示条数
            $store_id = $this->request->post('store_id');  //门店id
            $res=GoodsType::where('store_ids',$store_id)->order("weigh", "asc")->paginate(["page" => $page, "list_rows" => $limit]);
            $this->success("success", $res);
    }
    public function shop_cate_show(){
         $id = $this->request->post('id');  //分类id
            $res=GoodsType::where('id',$id)->find();
            $this->success("success", $res);
    }
    //添加编辑分类
    public function add_shop_cate(){
        $id = $this->request->post('id');  //分类id
        $store_id = $this->request->post('store_id');  //门店id
        $name = $this->request->post('name');  //分类名称
        $weigh = $this->request->post('weigh')??0;  //权重 排序
        
        $state = $this->request->post('state');  //状态值  0=禁用 1=正常
      

               //数据入库
               Db::startTrans();
               try {
                   // 提交事务
                    //新增分类
                    if (empty($id)) {
                          //查询门店属于哪个商户
                        $merchant_id=FzdcStore::where('id',$store_id)->value('merchant_id')??0;
                        $data=[
                            'name'=>$name,
                            'store_ids'=>$store_id,
                            'state'=>$state,
                            'weigh'=>$weigh,
                            'merchant_id'=>$merchant_id
                        ];
                        GoodsType::create($data);
                    }else{
                        //修改分类
                        $data=[
                            'name'=>$name,
                            'state'=>$state,
                            'weigh'=>$weigh,
                        ];
                        GoodsType::update($data,['id'=>$id]);
                    }
                  
                    Db::commit();
                
                } catch (\Exception $e) {
                    Log::error("订单创建失败:". $e->getMessage(). " Line:". $e->getLine());
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                
                    $this->success("success");
    
      
       
    }

    /**
     * 获取店铺资料
     */
    public function store_info()
    {
         $store_id=$this->request->post("store_id") ?? "0";
         if ( $store_id<=0) {
            $this->error("门店错误");
        }
        $user_id = $this->auth->id;

        $store = Store::get($store_id);
        $arr['user_type'] = 1; //默认是店长

   
        // //判断该用户关联的店铺
        // $res = \app\admin\model\fzdc\store\User::where(["user_id" => $user_id])->find();
        // if (!$res) {
        //     $this->error("该用户尚未关联店铺");
        // }
        // if ($res['status'] != "normal") {
        //     $this->error("该用户账号状态不正确");
        // }
        // $store = Store::get($res['store_id']);
        $arr = [];
        //用户角色
        // $arr['user_type'] = $res['order_type'];
        //店铺名字
        $arr['id'] = $store['id'];
        $arr['title'] = $store['title'];
        //余额
        $arr['balance'] = $store['balance'];
        //营业开关
//        if (time()>=strtotime(date("Y-m-d ").$store['start_times']) && time()<=strtotime(date("Y-m-d ").$store['end_times'])){
//            $arr['trade_switch'] = 1;
//        }else{
//            $arr['trade_switch'] = 0;
//        }
        $arr['trade_switch'] = $store->trade_switch;
//        $store->trade_switch = $arr['trade_switch'];
//        $store->save();
//        $arr['trade_switch'] = $store['trade_switch'];
        //认证状态
        $arr['authentication'] = $store['authentication'];
        //收藏数
        $arr['collection_count'] = StoreCollect::where(["store_id" => $store['id']])->count();
        //今日收益
        $today_order_ids = Detail::where(["score_id" => $store['id']])->whereTime("createtime", 'd')->column("order_id");
        $arr['day_money'] = \app\admin\model\fzdc\order\Order::whereIn('id', $today_order_ids)->where(["status" => 3])->sum('order_amount_total');
        //昨日收益
        $y_order_ids = Detail::where(["score_id" => $store['id']])->whereTime("createtime", 'yesterday')->column("order_id");
        $arr['y_day_money'] = \app\admin\model\fzdc\order\Order::whereIn('id', $y_order_ids)->where(["status" => 3])->sum('order_amount_total');
        //联系人
        $arr['contacts'] = $store['contacts'];
        //联系电话
        $arr['tel'] = $store['tel'];
        //店铺别名
        $arr['alias_title'] = $store['alias_title'];
        //店铺地址
        $arr['address'] = $store['address'];
        //缩略图
        $store['image'] = cdnurl($store['image'], true);
        $arr['image'] = $store['image'];
        //营业开始时间
        $arr['start_times'] = $store['start_times'];
        //营业结束时间
        $arr['end_times'] = $store['end_times'];
        //待支付订单数
        $detail = Detail::where(["score_id" => $store['id']])->whereTime("createtime", 'd')->column("order_id");
        $arr['to_paid'] = \app\admin\model\fzdc\order\Order::where(["status" => 1])->whereIn("id", $detail)->count();
        //待接单订单数
        $arr['to_pending'] = \app\admin\model\fzdc\order\Order::where(["business_status" => 1,"type"=>1])->whereNotIn("status", 3)->whereIn("id", $detail)->count();
        //已接单订单数
        $arr['already_pending'] = \app\admin\model\fzdc\order\Order::where(["business_status" => 2])->whereIn("id", $detail)->count();
        //待取单订单数
        $arr['to_picking'] = \app\admin\model\fzdc\order\Order::where(["status" => 8])->whereIn("id", $detail)->count();
        //待退款订单数
        $arr['to_refund'] = \app\admin\model\fzdc\order\Order::where(["status" => 4])->whereIn("id", $detail)->count();
        //已退款订单数
        $arr['already_refund'] = \app\admin\model\fzdc\order\Order::where(["status" => 9])->whereIn("id", $detail)->count();
        //已完成订单数
        $arr['already_over'] = \app\admin\model\fzdc\order\Order::where(["status" => 3])->whereTime("createtime", "d")->whereIn("id", $detail)->count();

        //今日营业额
        $arr['today']['money_total'] = \app\admin\model\fzdc\order\Order::where(["status" => 3])->whereIn("id", $today_order_ids)->sum('order_amount_total');
        //今日订单数
        $arr['today']['order_counts'] = \app\admin\model\fzdc\order\Order::where(["status" => 3])->whereIn("id", $today_order_ids)->count();
        //今日访客数
        $arr['today']['visitor_counts'] = View::where(["store_id" => $store['id']])->whereTime("createtime", "d")->count();
        //今日退单
        $arr['today']['refund_counts'] = \app\admin\model\fzdc\order\Order::where(["status" => 9])->whereIn("id", $today_order_ids)->count();

        //店铺收藏数
        $arr['store']['collect_counts'] = StoreCollect::where(["store_id" => $store['id']])->count();
        //商品点击数
        $arr['store']['cleck_goods_counts'] = $store['cleck_goods_counts'];
        //成交人数
        $arr['store']['people_number'] = \app\admin\model\fzdc\order\Order::where(["status" => 3])->whereIn("id", $detail)->group('user_id')->count();
        //退款金额
        $arr['store']['refund_money'] = \app\admin\model\fzdc\order\Order::where(["status" => 9])->whereIn("id", $detail)->sum("order_amount_total");
        //剩余可提现金额
        $else = Withdrawal::order("id", "desc")->find();
        if ($else) {
            $arr['remaining_amount'] = $else['residue_amount'];
        } else {
            $arr['remaining_amount'] = $store['balance'];
        }

        $this->success("success", $arr);
    }

    /**
     * 修改店铺资料
     */
    public function store_update()
    {
        $user_id = $this->auth->id;
        //判断该用户关联的店铺
        $res = \app\admin\model\fzdc\store\User::where(["user_id" => $user_id])->find();
        if (!$res) {
            $this->error("该用户尚未关联店铺");
        }
        if ($res['status'] != "normal") {
            $this->error("该用户账号状态不正确");
        }
        //判断身份
        if ($res['order_type'] != 1) {
            $this->error("没有权限添加");
        }
        $contacts = $this->request->post("contacts") ?? "";   //联系人
        $tel = $this->request->post("tel") ?? "";   //联系电话
        $title = $this->request->post("title") ?? "";   //店铺名称
        $alias_title = $this->request->post("alias_title") ?? "";   //店铺别名
        $address = $this->request->post("address") ?? "";   //地址
        $image = $this->request->post("image") ?? "";   //缩略图
        $start_times = $this->request->post("start_times") ?? "";   //营业开始时间
        $end_times = $this->request->post("end_times") ?? "";   //营业结束时间
        if (empty($contacts)) {
            $this->error("联系人不能为空");
        }
        if (empty($tel)) {
            $this->error("联系电话不能为空");
        }
        if (!$tel || !Validate::regex($tel, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        if (empty($title)) {
            $this->error("店铺名称不能为空");
        }
        if (empty($alias_title)) {
            $this->error("店铺别名不能为空");
        }
        if (empty($address)) {
            $this->error("地址不能为空");
        }
        if (empty($image)) {
            $this->error("缩略图不能为空");
        }
        if (empty($start_times)) {
            $this->error("营业开始时间不能为空");
        }
        if (empty($end_times)) {
            $this->error("营业结束时间不能为空");
        }
        $res = Store::get($res['store_id']);
        $res->contacts = $contacts;
        $res->tel = $tel;
        $res->title = $title;
        $res->alias_title = $alias_title;
        $res->address = $address;
        $res->image = $image;
        $res->start_times = $start_times;
        $res->end_times = $end_times;
        $res->save();
        $this->success("修改成功");

    }

    /**
     * 店铺认证
     */
    public function store_authentication()
    {
        $user_id = $this->auth->id;
        //判断该用户关联的店铺
        $res = \app\admin\model\fzdc\store\User::where(["user_id" => $user_id])->find();
        if (!$res) {
            $this->error("该用户尚未关联店铺");
        }
        if ($res['status'] != "normal") {
            $this->error("该用户账号状态不正确");
        }

        $type = $this->request->post("type") ?? "view";   //view=查看 apply=申请
        //判断身份
        if ($res['order_type'] != 1 && $type != 'view') {
            $this->error("没有权限添加");
        }
        $auth_res = Auther::where(["store_id" => $res['store_id']])->find();
        if ($type == 'view') {
            if ($auth_res) {
                $auth_res['store_image'] = cdnurl($auth_res['store_image'], true);
                $auth_res['yy_image'] = cdnurl($auth_res['yy_image'], true);
                $auth_res['font_image'] = cdnurl($auth_res['font_image'], true);
                $auth_res['back_image'] = cdnurl($auth_res['back_image'], true);
                $auth_res['hard_image'] = cdnurl($auth_res['hard_image'], true);
                $auth_res['self_image'] = cdnurl($auth_res['self_image'], true);
                $data = $auth_res;
            } else {
                $data = [];
            }
        } else {
            if ($auth_res){
                if ($auth_res['status'] == 1) {
                    $this->error("已认证");
                }
                if ($auth_res['status'] == 0) {
                    $this->error("审核中");
                }
            }

            $title = $this->request->post("title") ?? "";   //姓名
            $id_number = $this->request->post("id_number") ?? "";   //身份证号
            $mobile = $this->request->post("mobile") ?? "";   //号码
            $store_image = $this->request->post("store_image") ?? "";   //店铺图片
            $yy_image = $this->request->post("yy_image") ?? "";   //营业执照
            $font_image = $this->request->post("font_image") ?? "";   //身份证正面
            $back_image = $this->request->post("back_image") ?? "";   //身份证反面
            $hard_image = $this->request->post("hard_image") ?? "";   //手持身份证
            $self_image = $this->request->post("self_image") ?? "";   //个人自拍照
            if (!$mobile || !Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('手机号不正确'));
            }
            if (empty($title)) {
                $this->error("姓名不能为空");
            }
            if (empty($id_number)) {
                $this->error("身份证号不能为空");
            }
            if ($auth_res) {
                Auther::where(["id" => $auth_res['id']])->update([
                    "store_id" => $res['store_id'],
                    "title" => $title,
                    "id_number" => $id_number,
                    "mobile" => $mobile,
                    "status" => 0,
                    "store_image" => $store_image,
                    "yy_image" => $yy_image,
                    "font_image" => $font_image,
                    "back_image" => $back_image,
                    "hard_image" => $hard_image,
                    "self_image" => $self_image,
                    "createtime" => time(),
                    "updatetime" => time(),
                ]);
            } else {
                Auther::create([
                    "store_id" => $res['store_id'],
                    "title" => $title,
                    "id_number" => $id_number,
                    "mobile" => $mobile,
                    "store_image" => $store_image,
                    "yy_image" => $yy_image,
                    "font_image" => $font_image,
                    "back_image" => $back_image,
                    "hard_image" => $hard_image,
                    "self_image" => $self_image,
                    "createtime" => time(),
                    "updatetime" => time(),
                ]);
            }

            $data = [];
        }
        $this->success("success", $data);
    }

    /**
     * 修改店铺营业状态
     */
    public function trade_switch()
    {
        $user_id = $this->auth->id;
        $switch = $this->request->post("switch") ?? 1;   //0关 1开
        if ($switch) {
            $switch = 1;
        } else {
            $switch = 0;
        }
        //判断该用户关联的店铺
        $res = \app\admin\model\fzdc\store\User::where(["user_id" => $user_id])->find();
        if (!$res) {
            $this->error("该用户尚未关联店铺");
        }
        if ($res['status'] != "normal") {
            $this->error("该用户账号状态不正确");
        }
        Store::where(["id" => $res['store_id']])->update(["trade_switch" => $switch]);
        $this->success("修改成功");
    }

    /**
     * 添加提现账号
     */
    public function add_withdrawal_account()
    {
        $user_id = $this->auth->id;
        //判断该用户关联的店铺
        $res = \app\admin\model\fzdc\store\User::where(["user_id" => $user_id])->find();
        if (!$res) {
            $this->error("该用户尚未关联店铺");
        }
        if ($res['status'] != "normal") {
            $this->error("该用户账号状态不正确");
        }
        //判断身份
        if ($res['order_type'] != 1) {
            $this->error("没有权限添加");
        }
        $type = $this->request->post("type") ?? 1;   //1=银行卡 2=微信 3=支付宝
        if ($type == 1) {
            $bank_code = $this->request->post('bank_code'); //银行卡号
            $bank_mobile = $this->request->post('bank_mobile'); //银行卡预留手机号
            $code = $this->request->post('code'); //短信验证码
            if (empty($bank_code)) {
                $this->error("银行卡号不能为空");
            }
            if (empty($bank_mobile)) {
                $this->error("银行卡预留手机号不能为空");
            }
            if (empty($code)) {
                $this->error("短信验证码不能为空");
            }
            $ret = Smslib::check($bank_mobile, $code, 'register');
            if (!$ret && $code != '0000') {
                $this->error("短信验证码不正确");
            }
            //根据银行卡号得到银行卡名称
            $band_res = $this->checkLuhn($bank_code);
            if (!$band_res) {
                $this->error("银行卡格式错误");
            }
            $result = Http::get("https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo={$bank_code}&cardBinCheck=true");
            $result = json_decode($result, true);
            if (empty($result) || !is_array($result)) {
                $this->error("服务异常");
            }
            $bank_name = isset(self::$bank_info[$result['bank']]) ? self::$bank_info[$result['bank']] : '';  // 银行名称
            $bank_icon = isset(self::$card_icon[$result['bank']]) ? self::$card_icon[$result['bank']] : '';  // 银行图标
            $bran_type = self::$card_type[$result['cardType']];

            //添加银行卡
            Bank::create([
                "user_id" => $user_id,
                "store_id" => $res['store_id'],
                "type" => 1,
                "bank_name" => $bank_name,
                "bank_icon" => $bank_icon,
                "bank_type" => $bran_type,
                "bank_code" => $bank_code,
                "bank_mobile" => $bank_mobile,
                "status" => 0,
                "createtime" => time(),
                "updatetime" => time(),
            ]);

        } else {
            $code = $this->request->post('zh_code');               // 账号
            $img = $this->request->post('img');                 // 收款码
            if (empty($code)) {
                $this->error("账号不正确");
            }
            if (empty($img)) {
                $this->error("收款码不正确");
            }
            if ($type == 2) {
                //添加收款码
                Bank::create([
                    "user_id" => $user_id,
                    "store_id" => $res['store_id'],
                    "type" => $type,
                    "wx_code" => $code,
                    "wx_img" => $img,
                    "status" => 0,
                    "createtime" => time(),
                    "updatetime" => time(),
                ]);
            } else {
                //添加收款码
                Bank::create([
                    "user_id" => $user_id,
                    "store_id" => $res['store_id'],
                    "type" => $type,
                    "zfb_code" => $code,
                    "zfb_img" => $img,
                    "status" => 0,
                    "createtime" => time(),
                    "updatetime" => time(),
                ]);
            }

        }
        $this->success("提交成功");


    }

    function checkLuhn($card)
    {
        $len = strlen($card);
        $all = [];
        $sum_odd = 0;
        $sum_even = 0;
        for ($i = 0; $i < $len; $i++) {
            $all[] = substr($card, $len - $i - 1, 1);
        }
        //all 里的偶数key都是我们要相加的奇数位
        for ($k = 0; $k < $len; $k++) {
            if ($k % 2 == 0) {
                $sum_odd += $all[$k];
            } else {
                //奇数key都是要相加的偶数和
                if ($all[$k] * 2 >= 10) {
                    $sum_even += $all[$k] * 2 - 9;
                } else {
                    $sum_even += $all[$k] * 2;
                }
            }
        }
        $total = $sum_odd + $sum_even;
        if ($total % 10 == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 解绑提现账号
     */
    public function del_withdrawal_account()
    {
        $user_id = $this->auth->id;
        //判断该用户关联的店铺
        $res = \app\admin\model\fzdc\store\User::where(["user_id" => $user_id])->find();
        if (!$res) {
            $this->error("该用户尚未关联店铺");
        }
        if ($res['status'] != "normal") {
            $this->error("该用户账号状态不正确");
        }
        //判断身份
        if ($res['order_type'] != 1) {
            $this->success("没有权限解绑");
        }
        $id = $this->request->post("id");   //提现账号
        if (!$id) {
            $this->error("账号id不能为空");
        }
        $res = Bank::get($id);
        if (!$res) {
            $this->error("提现账户不存在");
        }
        Bank::destroy($id);
        $this->success("解绑成功");

    }

    /**
     * 获取提现账号列表
     */
    public function withdrawal_account_list()
    {
        $user_id = $this->auth->id;
        //判断该用户关联的店铺
        $res = \app\admin\model\fzdc\store\User::where(["user_id" => $user_id])->find();
        if (!$res) {
            $this->error("该用户尚未关联店铺");
        }
        if ($res['status'] != "normal") {
            $this->error("该用户账号状态不正确");
        }
        $data = Bank::where(["store_id" => $res['store_id'],"status"=>1])->select()
            ->each(function ($item) {
                if ($item->type == 1) {
					if ($item->bank_icon){
                        $img = "./" . $item->bank_icon;
                        $average = new \Imagick($img);
                        $average->quantizeImage(10, \Imagick::COLORSPACE_RGB, 0, false, false);
                        $average->uniqueImageColors();

                        $colorarr = $this->GetImagesColor($average);
                        $r = $g = $b = 0;
                        foreach ($colorarr as $val) {
                            $r += $val['r'];
                            $g += $val['g'];
                            $b += $val['b'];
                        }
                        $r = round($r / 10);
                        $g = round($g / 10);
                        $b = round($b / 10);
                        $item->rgb = "rgb({$r},{$g},{$b})";
                    }else{
                        $item->rgb = "rgb(255,255,255)";
                    }
                } elseif ($item->type == 2) {
                    $item->rgb = "#00C2A0";
                } else {
                    $item->rgb = "#6C80FF";
                }
                $item->bank_icon = cdnurl($item->bank_icon, true);
            });
        $this->success("success", $data);
    }

    function GetImagesColor(\Imagick $im)
    {
        $colorarr = array();
        $it = $im->getPixelIterator();
        $it->resetIterator();
        while ($row = $it->getNextIteratorRow()) {
            foreach ($row as $pixel) {
                $colorarr[] = $pixel->getColor();
            }
        }
        return $colorarr;
    }

    /**
     * 发起提现
     */
    public function withdrawal()
    {
        $user_id = $this->auth->id;
        //判断该用户关联的店铺
        $res = \app\admin\model\fzdc\store\User::where(["user_id" => $user_id])->find();
        if (!$res) {
            $this->error("该用户尚未关联店铺");
        }
        if ($res['status'] != "normal") {
            $this->error("该用户账号状态不正确");
        }
        //判断身份
        if ($res['order_type'] != 1) {
            $this->error("没有权限");
        }
        $detail = Userdetail::get(["user_id" => $user_id]);
        $bank_id = $this->request->post('bank_id'); //提现账号
        $money = $this->request->post('money'); //提现金额
        $bank_res = Bank::get($bank_id);
        if (!$bank_res) {
            $this->error("提现账号不存在");
        }
        $store = Store::get($res['store_id']);
        if ($money<=0){
            $this->error("提现金额不能小于等于0");
        }
        if ($money > $store['balance']) {
            $this->error("提现金额不能大于余额");
        }
        if ($detail['aliuid'] == '' && $bank_res['type'] == 3) {
            $this->error("支付宝账号没有绑定，请绑定支付宝账号", '', 3);
        }

        if ($detail['openid'] == '' && $bank_res['type'] == 2) {
            $this->error("微信账号没有绑定，请绑定支付宝账号", '', 3);
        }
        $with_res = Withdrawal::get(["store_id" => $res['store_id'], "status" => 0]);
        if ($with_res) {
            $this->error("请等待上次提现结果审核");
        }
        Withdrawal::create([
            "store_id" => $res['store_id'],
            "user_id" => $user_id,
            "amount" => $money,
            "residue_amount" => bcsub($store['balance'], $money, 2),
            "type" => $bank_res['type'],
            "month" => date("Y-m"),
            "createtime" => time(),
            "updatetime" => time(),
        ]);
        $idx = Withdrawal::getLastInsID();


        $this->success("提交成功");

    }

    /**
     * 获取提现明细
     */
    public function withdrawal_detail()
    {
        $page = $this->request->post('page') ?? 1;  //页码
        $limit = $this->request->post('limit') ?? 6; //每页显示条数
        $user_id = $this->auth->id;
        //判断该用户关联的店铺
        $res = \app\admin\model\fzdc\store\User::where(["user_id" => $user_id])->find();
        if (!$res) {
            $this->error("该用户尚未关联店铺");
        }
        if ($res['status'] != "normal") {
            $this->error("该用户账号状态不正确");
        }
        $date = Withdrawal::where(["store_id" => $res['store_id']])->page($page, $limit)->group('month')->column('month');
        $arr = [];
        if (!empty($date)) {
            foreach ($date as $dk => $dv) {
                $arr[$dk]['date'] = $dv;
                $arr[$dk]['data'] = Withdrawal::where(["month" => $dv])->order("id", "desc")->select();
            }
        }
        $this->success("success", $arr);
    }

    /**
     * 订单列表
     */
    public function order_list()
    {
        $user_id = $this->auth->id;
        //判断该用户关联的店铺
        // $res = \app\admin\model\fzdc\store\User::where(["user_id" => $user_id])->find();
        // if (!$res) {
        //     $this->error("该用户尚未关联店铺");
        // }
        // if ($res['status'] != "normal") {
        //     $this->error("该用户账号状态不正确");
        // }

        $page = $this->request->post('page') ?? 1;  //页码
        $limit = $this->request->post('limit') ?? 10; //每页显示条数
        $status = $this->request->post('status') ?? ""; //状态 1=待接单 2=已接单 3=已完成 4=待退款,5=待付款,6=已退款
        $search = $this->request->post('search') ?? ""; //搜索条件
        $type = $this->request->post('type');
        $store_id = $this->request->post('store_id')?? 0; //增加了一个指定门店的
        $where = [];
        if ($type != 4) {
            if ($status) {
                if (in_array($status, [1, 2])) {
                    $where['business_status'] = ["=", $status];
                    $where['status'] = ["in", [6,1]];
                } else {
                    if (in_array($status, [3, 4])) {
                        $where['status'] = ["=", $status];
                    } elseif ($status == 5) {
                        $where['status'] = ["=", 1];
                    } else {
                        $where['status'] = ["=", 9];
                    }
                }
            }
        } else {
            if ($status) {
                $where['status'] = ["=", $status];
            }
        }

        if ($search) {
            $where['order_no|subscribe_tel'] = ['like', "%" . $search . "%"];
        }
        if ($type == 0) {
            $where['order_type'] = ["in", [1, 2, 3]];
        } else {
            $where['order_type'] = ["in", [4]];
        }
        $where['type'] = ["in", [1]];
        //改成了指定的门店id
        // $where['store_id'] = ['=',$res['store_id']];
        $where['store_id'] = ['=',$store_id];
        $data = \app\admin\model\fzdc\order\Order::where($where)->order("id", "desc")->field('id,status,user_id,coupon_id,business_status,order_no,subscribe_tel,code,order_type,createtime,order_amount_total,remark,seat_id,subscribe_name,dd_time,subscribe_time,dc_type,p_type')->paginate(["page" => $page, "list_rows" => $limit])
            ->each(function ($item) {
                $user = \app\admin\model\User::get($item->user_id);
                if ($user) {
                    $item->username = $user['username'];
                    $item->avatar = cdnurl($user['avatar'], true);
                } else {
                    $item->username = "";
                    $item->avatar = "";
                }

                if ($item->seat_id) {
                    $seat = Sear::whereIn('id',$item->seat_id)->select();
                    $seat_info = [];
                    if ($seat) {
                        foreach ($seat as $sk => $s){
                            $seat_info[$sk]['seat_title'] = $s['title'];
                            $seat_info[$sk]['seat_no'] = $s['no'];
                            if ($s['img']) {
                                $seat_info[$sk]['seat_img'] = cdnurl($s['img'], true);
                            } else {
                                $seat_info[$sk]['seat_img'] = "";
                            }
                        }
                    }
                    $item->seat_info = $seat_info;
                }

                $item->detail = Detail::where(["order_id" => $item['id']])->field("goods_id,goods_name,item_name,goods_count,goods_price,goods_prices")->select()
                    ->each(function ($ite) {
                        $goods = Goods::get($ite->goods_id);
                        if($goods){
                            $ite->goods_img = cdnurl($goods['image'], true);
                        }else{
                            $ite->goods_img = "";
                        }

                    });
                $coupon_money = 0;
                if ($item->coupon_id) {
                    $coupon_money = Coupon::get($item->coupon_id)['used_amount'];
                }
                $item->coupon_money = $coupon_money;
                $item->heg = "320rpx";
                if (empty($item->subscribe_tel)){
                    $item->subscribe_tel = \app\admin\model\fzdc\user\User::where("id", $item->user_id)->value("mobile");
                }
                $item->hidden(["user_id", "coupon_id"]);
            });
        $this->success("success", $data);
    }

    /*
     * 测试打印机打印
     */
    public function test_print()
    {
        \addons\fzdc\library\printer::test();
    }


    /**
     * 订单详情
     */
    public function order_detail()
    {
        $id = $this->request->post('id');  //订单id
        if (empty($id)) {
            $this->error("订单id不能为空");
        }
        $res = \app\admin\model\fzdc\order\Order::get($id);
        if (!$res) {
            $this->error("订单不存在");
        }
        $res['detail'] = Detail::where(["order_id" => $id])->where(['numbers' => 1])->field("id,user_id,goods_id,goods_name,item_name,goods_count,goods_price,goods_prices,numbers,is_sc")->select()
            ->each(function ($ite) {
                $goods = Goods::get($ite->goods_id);
                $ite->goods_img = cdnurl($goods['image'], true);
                $user = \app\admin\model\User::get($ite->user_id);
                if ($user) {
                    $ite->username = $user['username'];
                    $ite->mobile = $user['mobile'];
                    $ite->avatar = cdnurl($user['avatar'], true);
                } else {
                    $ite->username = "";
                    $ite->avatar = "";
                    $ite->mobile = "";
                }
            });
        $else_detail = Detail::where(["order_id" => $id])->where("numbers", ">", 1)->field("id,user_id,goods_id,goods_name,item_name,goods_count,goods_price,goods_prices,numbers,is_sc")->select()
            ->each(function ($ite) {
                $goods = Goods::get($ite->goods_id);
                $ite->goods_img = cdnurl($goods['image'], true);
                $user = \app\admin\model\User::get($ite->user_id);
                if ($user) {
                    $ite->username = $user['username'];
                    $ite->mobile = $user['mobile'];
                    $ite->avatar = cdnurl($user['avatar'], true);
                } else {
                    $ite->username = "";
                    $ite->avatar = "";
                    $ite->mobile = "";
                }
            });
        if ($else_detail) {
            $else_detail = $else_detail->toArray();
            //对二维数组else_detail进行处理，根据numbers进行分组
            $groupByField = 'numbers';
            $groupedArray = array_reduce($else_detail, function ($carry, $item) use ($groupByField) {
                $carry[$item[$groupByField]][] = $item;
                return $carry;
            }, []);
            $else_detail = [];
            foreach ($groupedArray as $gk => $gv) {
                $else_detail[$gk]['numbers'] = $gk;
                $else_detail[$gk]['detail'] = $gv;
                $else_detail[$gk]['count'] = count($gv);
                $else_detail[$gk]['is_sc'] = $gv[0]['is_sc'];
                $else_detail[$gk]['username'] = $gv[0]['username'];
                $else_detail[$gk]['avatar'] = $gv[0]['avatar'];

            }
            $else_detail = array_merge($else_detail);
        }
        $res['else_detail'] = $else_detail;
        $coupon_money = 0;
        if ($res['coupon_id']) {
            $coupon_money = Coupon::get($res['coupon_id'])['used_amount'];
        }


        if ($res['order_type'] == 4 || $res['order_type'] == 3 || $res['seat_id']) {
            $seat = Sear::whereIn('id',$res['seat_id'])->select();
            $seat_info = [];
            if ($seat) {
                foreach ($seat as $sk => $s){
                    $seat_info[$sk]['seat_title'] = $s['title'];
                    $seat_info[$sk]['seat_no'] = $s['no'];
                    if ($s['img']) {
                        $seat_info[$sk]['seat_img'] = cdnurl($s['img'], true);
                    } else {
                        $seat_info[$sk]['seat_img'] = "";
                    }
                }
            }
            $res['seat_info'] = $seat_info;
        }
        //如果是外卖订单
        if($res['order_type']==2){
            $address_info = \app\admin\model\fzdc\Address::get($res['address_id']);
            if ($address_info) {
                $res['address'] = $address_info['title'] . " " . $address_info['mobile'] . " " . $address_info['address'] . " " . $address_info['remark'];
            } else {
                $res['address'] = "";

            }
        }
        $res['coupon_money'] = $coupon_money;
        $res->hidden(["user_id", "store_id", "address_id", "coupon_id", "cart_ids", "logistics_fee", "out_trade_no", "service_time", "tableware_count", "confirm_time"]);

        $this->success("success", $res);
    }

    /**
     * 接单
     */
    public function receiving_orders()
    {
        $user_id = $this->auth->id;

        //判断该用户关联的店铺
        $s_res = \app\admin\model\fzdc\store\User::where(["user_id" => $user_id])->find();
        if (!$s_res) {
            $this->error("该用户尚未关联店铺");
        }
        if ($s_res['status'] != "normal") {
            $this->error("该用户账号状态不正确");
        }
        $id = $this->request->post('id');  //订单id
        if (empty($id)) {
            $this->error("订单id不能为空");
        }
        $res = \app\admin\model\fzdc\order\Order::get($id);
        if (!$res) {
            $this->error("订单不存在");
        }
        //判断订单状态
        if ($res['p_type'] == 1) {
            if ($res['status'] != 6) {
                $this->error("订单状态不正确");
            }
        }

//        if ($res['order_type'] == 3) {
//            $this->success("堂食订单，无需接单");
//        }


        if ($res['business_status'] == 2) {
            $this->success("已接单");
        }
        $res->business_status = 2;
        $res->save();
        $store = Store::where(["id" => $s_res['store_id']])->find();

        $order_detail = Detail::where(["order_id" => $id])->select();
        $cp = "";
        if (!$order_detail){
            $cp = $store['title'];
        }else{
            foreach ($order_detail as $k => $v) {
                if ($k == count($order_detail)-1){
                    $cp .= $v['goods_name'];
                }else{
                    $cp .= $v['goods_name'].",";
                }
            }
        }

        //判断用户是否订阅消息推送
        $userInfo = Userdetail::get(["user_id" => $res->user_id]);
        Log::info("推送订单状态消息开始");
        if ($userInfo['subscribe'] == 1) {
            Log::info("进入订单状态推送1");
            $message = Push::where(["type" => 3])->find();
            if ($message) {
                Log::info("进入订单状态推送2");
                if (!empty($message['multiplejson'])) {
                    $json = json_decode($message['multiplejson'], true);
                    //参数名对应订阅消息详细内容参数 （以下为测试）
                    $data = [];
                    foreach ($json as $jv) {
                        switch ($jv['title']) {
                            case '2':
                                $data['data'][$jv['keyword']]['value'] = $res->order_no;
                                break;
                            case '9':
                                $data['data'][$jv['keyword']]['value'] = $cp;
                                break;
                            case '8':
                                $data['data'][$jv['keyword']]['value'] = "已接单";
                                break;
                            case '4':
                                $data['data'][$jv['keyword']]['value'] = date("Y-m-d H:i:s", $res->pay_time);
                                break;
                            case '5':
                                $data['data'][$jv['keyword']]['value'] = $store['title'];
                                break;

                        }
                    }
                    Log::info("订单状态推送数据：" . json_encode($data['data']));
                    $data['order_id'] = $res['id'];
                    $data['openid'] = $userInfo['openid'];
                    $data['masterplate'] = $message->masterplate;
                    Queue::later(2, 'addons\fzdc\job\SendMessage', $data, 'dcOrderQueue');
                }

            }

        }


        $this->success("接单成功");
    }

    /**
     * 商家加减菜
     */
    public function add_reduce_menu()
    {
        $user_id = $this->auth->id;
        //判断该用户关联的店铺
        $res = \app\admin\model\fzdc\store\User::where(["user_id" => $user_id])->find();
        if (!$res) {
            $this->error("该用户尚未关联店铺");
        }
        if ($res['status'] != "normal") {
            $this->error("该用户账号状态不正确");
        }
        $id = $this->request->post('id');  //订单id
        $detail_id = $this->request->post('detail_id');  //菜品详情id
        $type = $this->request->post('type');  //类型 1=加菜 2=减菜
        $num = $this->request->post('num') ?? 1;  //数量
        if (empty($id)) {
            $this->error("订单id不能为空");
        }
        $res = \app\admin\model\fzdc\order\Order::get($id);
        if (!$res) {
            $this->error("订单不存在");
        }
        //判断订单状态
        if ($res['status'] == 3 || $res['status'] == 4 || $res['status'] == 5 || $res['status'] == 8 || $res['status'] == 9) {
            $this->error("订单状态不正确");
        }
        $detail = Detail::where(["order_id" => $id, "id" => $detail_id])->find();
        if (!$detail) {
            $this->error("订单详情不存在");
        }
        $sku = SkuProduct::get(["key" => $detail['goods_item_id']]);
        if (!$sku) {
            $this->error("商品规格不存在");
        }
        if ($type == 1) {
            $sku->setInc("stock", $num);
            $detail->setInc("goods_count", $num);
            $res->order_amount_total = bcadd($res['order_amount_total'], bcmul($num, $sku['price'], 2), 2);
            $res->save();
            $this->success("加菜成功");
        } else {
            if ($num > $detail['goods_count']) {
                $this->error("减菜数量不能大于已购买数量");
            }
            if ($detail['goods_count'] == 1) {
                Detail::destroy($detail_id);
                $sku->setDec("stock", $num);
                $res->order_amount_total = bcsub($res['order_amount_total'], bcmul($num, $sku['price'], 2), 2);
                $res->save();
                $this->success("减菜成功");

            }
            $sku->setDec("stock", $num);
            $detail->setDec("goods_count", $num);
            $res->order_amount_total = bcsub($res['order_amount_total'], bcmul($num, $sku['price'], 2), 2);
            $res->save();
            $this->success("减菜成功");
        }
    }

    /**
     * 确认送出
     */
    public function send_out()
    {
        $id = $this->request->post('id');  //订单id
        $numbers = $this->request->post('numbers');  //次数
        if (empty($id)) {
            $this->error("订单id不能为空");
        }
        $res = \app\admin\model\fzdc\order\Order::get($id);
        if (!$res) {
            $this->error("订单不存在");
        }
        //判断订单状态
        if ($res['business_status'] != 2) {
            $this->error("订单未接单");
        }
        if ($res['status'] != 6 && $res['p_type'] != 2) {
            $this->error("订单状态不正确");
        }
        if ($res['order_type'] == 3 || $res['order_type'] == 1 || $res['order_type'] == 2){
            $res->status = 3;
        }else{
            $res->status = 7;
        }
        if ($res['p_type'] == 2){
            $res->status = 1;
        }
        if ($numbers){
            Detail::where(['order_id' => $id, 'numbers' => $numbers])->update(['is_sc' => 1]);
        }else{
            Detail::where(['order_id' => $id])->update(['is_sc' => 1]);
        }
        $res->save();
        //订单放入队列 处理自动收货完成
        $data = ["orderNo" => $res['order_no'], "type" => 2];
        Queue::later(bcmul($this->config['shtime'], 60), 'addons\fzdc\job\Overtime', $data, 'dcOrderQueue');
        $this->success("确认送出成功");
    }


    /**
     * 完成订单
     */
    public function over()
    {
        $id = $this->request->post('id');  //订单id
        if (empty($id)) {
            $this->error("订单id不能为空");
        }
        $res = \app\admin\model\fzdc\order\Order::get($id);
        if (!$res) {
            $this->error("订单不存在");
        }
//        if ($res['order_type']==3){
            $res->pay_type = 3;
//        }
        $res->status = 3;
        $res->save();
        if ($res['seat_id']){
            Sear::whereIn('id' , $res['seat_id'])->update(['use_status' => 1]);
        }
        $this->success("成功");
    }

    /**
     * 退款
     */
    public function refund()
    {
        $user_id = $this->auth->id;
        $id = $this->request->post('order_no');  //订单id
        $apply = $this->request->post('apply') ?? "";  //申请原因
        if (empty($id)) {
            $this->error("订单id不能为空");
        }
        $res = \app\admin\model\fzdc\order\Order::get(["order_no" => $id]);
        if (!$res) {
            $this->error("订单不存在");
        }
        //判断订单状态
        if ($res['status'] == 1 || $res['status'] == 3) {
            $this->error("订单状态不正确");
        }

        $refund_insert_data = [
            "order_id" => $res['id'],
            "store_id" => $res['store_id'],
            "amount" => $res['order_amount_total'],
            "user_id" => $res['user_id'],
            "refund_status" => 1,
            "apply" => $apply,
            "createtime" => time(),
            "updatetime" => time(),
        ];

        $st = \app\admin\model\fzdc\store\User::where(["user_id" => $user_id, "store_id" => $res['store_id']])->find();


        //判断是否钱包支付
        if ($res['pay_type'] == 2) {
            //查询退款开关
            if ($this->config['refund_switch'] || $st) {
                //退款到钱包
                //增加收入支出明细
                Revenue::create(["store_id" => $res['store_id'], "type" => 2, "amount" => $res['order_amount_total'], "user_id" => $res['user_id'], "createtime" => time(), "updatetime" => time()]);
                //增加退款流水
                $refund_insert_data['refund_status'] = 2;
                Refund::create($refund_insert_data);
                $store = Store::get($res['store_id']);
                $store->setDec("balance", $res['order_amount_total']);
                $store->save();
                $user = \app\admin\model\User::get($res['user_id']);
                $user->setInc("money", $res['order_amount_total']);
                $user->save();
                //判断是否有优惠券
                if ($res['coupon_id'] > 0) {
                    //更新优惠券为未使用，判断优惠券是否过期
                    $coupon = Coupon::get($res['coupon_id']);
                    if (time() > $coupon->end_time) {
                        $res5 = Receive::update(['state' => -1], ["user_id" => $res['user_id'], "coupon_id" => $res['coupon_id']]);
                    } else {
                        $res5 = Receive::update(['state' => 0], ["user_id" => $res['user_id'], "coupon_id" => $res['coupon_id']]);
                    }
                    Log::log("优惠券更新状态" . $res5);
                }
                //增加库存
                if ($res['cart_ids']) {
                    $ids = Detail::where(['order_id' => $res['id']])->column('id');
                    foreach ($ids as $v) {
                        $detail = Detail::where(["id" => $v])->find();
                        $sku = SkuProduct::get(["key" => $detail['goods_item_id']]);
                        if($sku){
                            $sku->setInc("stock", $detail['goods_count']);
                        }
                    }
                }
                if ($res->order_type == 4) {
                    $res->status = 5;
                } else {
                    $res->status = 9;
                }
                $res->apply = $apply;
                $res->save();
                $this->success("退款成功");
            }else{
                //手动退款
                $refund_insert_data['refund_status'] = 1;
                $res->apply = $apply;
                $res->last_status = $res->status;
                $res->status = 4;
                $res->save();
                Refund::create($refund_insert_data);
                $this->success("退款申请成功");
            }


        }


        //查询退款开关
        if ($this->config['refund_switch'] || $st) {
            //原路返回
            Db::startTrans();
            try {
                $res->apply = $apply;
                $order['transaction_id'] = $res['out_trade_no'];
                $order['out_refund_no'] = date('YmdHis') . substr(bcadd($id, strrev(date('YmdHis')), 0), -8) . bcadd($user_id, time(), 0);
                $order['total_fee'] = bcmul($res['order_amount_total'], 100, 0); // 原支付交易的订单总金额
                $order['refund_fee'] = bcmul($res['order_amount_total'], 100, 0); // 退款金额
                $order['notify_url'] = request()->domain() . "/addons/fzdc/order/refund_notifyx";
                $config = Service::getConfig();
                $pay = Pay::wechat($config);
                $result = $pay->refund($order);
                Log::info("退款结果：" . json_encode($result));
                if ($result['return_code'] == "SUCCESS") {
                    Log::info("退款成功，退款单号：" . $order['out_refund_no']);
                    if ($res->order_type == 4) {
                        $res->status = 5;
                    } else {
                        $res->status = 9;
                    }
                    $res->out_refund_no = $order['out_refund_no'];
                    $res->refund_id = $result['refund_id'];
                    $res->save();
                    //增加收入支出明细
                    Revenue::create(["store_id" => $res['store_id'], "type" => 2, "amount" => $res['order_amount_total'], "user_id" => $res['user_id'], "createtime" => time(), "updatetime" => time()]);
                    //增加退款流水
                    $refund_insert_data['refund_status'] = 2;
                    Refund::create($refund_insert_data);
                    //判断是否使用优惠券
                    if ($res['coupon_id'] > 0) {
                        //更新优惠券为未使用，判断优惠券是否过期
                        $coupon = Coupon::get($res['coupon_id']);
                        if (time() > $coupon->end_time) {
                            $res5 = Receive::update(['state' => -1], ["user_id" => $res['user_id'], "coupon_id" => $res['coupon_id']]);
                        } else {
                            $res5 = Receive::update(['state' => 0], ["user_id" => $res['user_id'], "coupon_id" => $res['coupon_id']]);
                        }
                        Log::log("优惠券更新状态" . $res5);
                    }
                    if ($res['cart_ids']) {
                        $ids = Detail::where(['order_id' => $res['id']])->column('id');
                        foreach ($ids as $v) {
                            $detail = Detail::where(["id" => $v])->find();
                            $sku = SkuProduct::get(["key" => $detail['goods_item_id']]);
                            if( $sku){
                                $sku->setInc("stock", $detail['goods_count']);
                            }
                        }
                    }
                } else {
                    $res->last_status = $res->status;
                    $res->status = 4;
                    $res->out_refund_no = $order['out_refund_no'];
                    $res->refund_id = $result['refund_id'];
                    $res->save();
                    //手动退款
                    $refund_insert_data['refund_status'] = 1;
                    Refund::create($refund_insert_data);
                }
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error("退款失败：" . $e->getMessage() . ",行号：" . $e->getLine() . ",文件：" . $e->getFile());
            }
        } else {
            //手动退款
            $refund_insert_data['refund_status'] = 1;
            $res->apply = $apply;
            $res->last_status = $res->status;
            $res->status = 4;
            $res->save();
            Refund::create($refund_insert_data);
        }

        $this->success("退款申请成功");
    }

    /**
     * 收入支出明细
     */
    public function revenue()
    {
        $user_id = $this->auth->id;
        //判断该用户关联的店铺
        $res = \app\admin\model\fzdc\store\User::where(["user_id" => $user_id])->find();
        if (!$res) {
            $this->error("该用户尚未关联店铺");
        }
        if ($res['status'] != "normal") {
            $this->error("该用户账号状态不正确");
        }
        $page = $this->request->post('page') ?? 1;  //页码
        $limit = $this->request->post('limit') ?? 10; //每页显示条数
        $date = $this->request->post('date') ?? ""; //年月
        if ($date) {
            $data = Revenue::where('FROM_UNIXTIME(createtime,"%Y-%m")="' . $date . '"')->paginate(["page" => $page, "list_rows" => $limit])
                ->each(function ($item) {
                    $user = \app\admin\model\User::get($item->user_id);
                    $item->username = $user['username'];
                });
        } else {
            $data = Revenue::where([])->paginate(["page" => $page, "list_rows" => $limit])
                ->each(function ($item) {
                    $user = \app\admin\model\User::get($item->user_id);
                    if ($user){
                        $item->username = $user['username'];
                    }else{
                        $item->username = "";
                    }
                });
        }
        $this->success("success", $data);
    }

    /*
     * 打印小票
     */
    public function print()
    {
        $data = $this->request->post();
        $order = \app\admin\model\fzdc\order\Order::get($data['id']);
        if (!$order) {
            $this->error("订单不存在");
        }
        $data['store_id'] = $order['store_id'];
        $storeInfo = Store::where("id", $data['store_id'])->find();

        //获取打印机配置

        if ($storeInfo['print_sn'] == '') {
            Log::info("商家没有配置打印机!");
            $this->error("商家没有配置打印机");
        }

        $print = Prin::get(["id" => $storeInfo['print_sn'], "status" => "normal"]);
        if (!$print) {
            Log::info("未获取到打印机配置");
            $this->error("未获取到打印机配置");
        }

        try {
            printer::printing($storeInfo, $print->id, $data['id'],1);
        } catch (\Throwable $e) {

            Log::info($e->getMessage());
            $this->error($e->getMessage());
        }

        Log::info("打印成功");
        $this->success("打印成功");
    }

    /*
     * 拒绝退款
     */
    public function resold_order()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error("缺少订单id");
        }
        $order = \app\admin\model\fzdc\order\Order::get($id);
        //判断订单状态
        if ($order['status'] != 4) {
            $this->error("订单状态不正确");
        }
        $order->status = $order->last_status;
        $order->save();
        Refund::where(['order_id' => $id])->delete();
        $this->success("success");
    }

}
